package org.travel_system.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.travel_system.utils.MinioUtil;

@Controller
public class DispatcherController {
    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/fileUpload")
    @ResponseBody
    public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file, HttpSession session) {
        if (file == null || file.isEmpty()) {
            return ResponseEntity.badRequest().body("上传的文件为空");
        }

        try {
            final String s = minioUtil.putObject(file);
            System.out.println(s);
            session.setAttribute("fileUrl", s);
            System.out.println(ResponseEntity.ok("文件上传成功：" + s));
            return ResponseEntity.ok(s);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取图片的路径【带问号后面的内容】
     * @param filename
     * @return
     */
    @ResponseBody
    @GetMapping("/fileDownload/{filename}")
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        minioUtil.getObject(filename,response);
    }
}
